import {Injectable} from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

import {HttpClient, HttpParams, HttpHeaders} from "@angular/common/http";


/*
 Generated class for the HttpService provider.
 用 @angular/common/http 实现，测试发现在iphone下依然调不通http请求，
 会报{"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null}

 See https://angular.io/docs/ts/latest/guide/dependency-injection.html
 for more info on providers and Angular 2 DI.

 ios版本发送https 请求错误问题
 1.移除插件cordova-plugin-ionic-webview
   ionic cordova plugin remove cordova-plugin-ionic-webview 1.1.16

 2.参考：http://blog.csdn.net/u012794461/article/details/50564383
 修改webstrom 工程platforms-->MyApp-->AppDelegate.m-->在末尾追加如下代码：
   @implementation NSURLRequest(DataController)
  + (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
  {
      return YES;
  }
  @end
 */
@Injectable()
export class HttpService {

  constructor(private http:HttpClient) {
    //console.log('Hello HttpService Provider');
  }

  //paramObj可传可不传
  public get(url: string, paramObj?: any) {
    if (paramObj) {
      let reqUrl = url + this.toQueryString(paramObj);
      console.log('reqUrl:' + reqUrl);
      // return this.http.get(reqUrl)
      //   .toPromise()
      //   .then(res => this.handleSuccess(res))
      //   .catch(error => this.handleError(error));

      return this.http.get(reqUrl)
        .toPromise();
    }
    else {
      console.log('reqUrl:' + url);
      // return this.http.get(url)
      //   .toPromise()
      //   .then(res => this.handleSuccess(res))
      //   .catch(error => this.handleError(error));

      return this.http.get(url)
        .toPromise();
    }

  }

  //form提交方式
  public postForm(url: string, paramObj: any) {
    let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
    let reqUrl = url;
    let pramaStr = JSON.stringify(paramObj);
    console.log('reqUrl:' + reqUrl);
    console.log('reqParam:' + JSON.stringify(paramObj));
    // return this.http.post(url, paramObj, {headers: headers})
    //   .toPromise()
    //   .then(res => this.handleSuccess(res))
    //   .catch(error => this.handleError(error));

    return this.http.post(url, paramObj, {headers: headers})
      .toPromise();
  }

  //json提交方式
  public postJson(url: string, paramObj: any) {
    let headers = new HttpHeaders({'Content-Type': 'application/json'});
    let reqUrl = url;
    let paramJson = JSON.stringify(paramObj);
    console.log('reqUrl:' + reqUrl);
    console.log('reqParam:' + paramJson);
    // return this.http.post(url, paramObj, {headers: headers})
    //   .toPromise()
    //   .then(res => this.handleSuccess(res))
    //   .catch(error => this.handleError(error));

    return this.http.post(url, paramObj, {headers: headers})
      .toPromise();
  }

  /**
   * @param obj　参数对象
   * @return {string}　参数字符串
   * @example
   *  声明: var obj= {'name':'小军',age:23};
   *  调用: toQueryString(obj);
   *  返回: "?name=%E5%B0%8F%E5%86%9B&age=23"
   */
  private toQueryString(obj) {
    let ret = [];
    for (let key in obj) {
      key = encodeURIComponent(key);
      let values = obj[key];
      if (values && values.constructor == Array) {//数组
        let queryValues = [];
        for (let i = 0, len = values.length, value; i < len; i++) {
          value = values[i];
          queryValues.push(this.toQueryPair(key, value));
        }
        ret = ret.concat(queryValues);
      } else { //字符串
        ret.push(this.toQueryPair(key, values));
      }
    }
    return '?' + ret.join('&');
  }

  /**
   *
   * @param obj
   * @return {string}
   *  声明: var obj= {'name':'小军',age:23};
   *  调用: toQueryString(obj);
   *  返回: "name=%E5%B0%8F%E5%86%9B&age=23"
   */
  // private toBodyString(obj) {
  //   let ret = [];
  //   for (let key in obj) {
  //     key = encodeURIComponent(key);
  //     let values = obj[key];
  //     if (values && values.constructor == Array) {//数组
  //       let queryValues = [];
  //       for (let i = 0, len = values.length, value; i < len; i++) {
  //         value = values[i];
  //         queryValues.push(this.toQueryPair(key, value));
  //       }
  //       ret = ret.concat(queryValues);
  //     } else { //字符串
  //       ret.push(this.toQueryPair(key, values));
  //     }
  //   }
  //   return ret.join('&');
  // }

  private toQueryPair(key, value) {
    if (typeof value == 'undefined') {
      return key;
    }
    return key + '=' + encodeURIComponent(value === null ? '' : String(value));
  }

  private handleSuccess(result: any) {
    console.log('respInfo:' + JSON.stringify(result));
    return result; //返回对象
  }

  private handleError(error: any) {
    console.log('respInfo handleError:' + JSON.stringify(error));
    let msg = '请求失败';
    if (error.status == 0) {
      msg = '请求地址错误';
    }
    if (error.status == 400) {
      msg = '请求无效';
      console.log('请检查参数类型是否匹配');
    }
    if (error.status == 404) {
      msg = '请求资源不存在';
      console.error(msg + '，请检查路径是否正确');
    }
    console.log(error);
    //alert(msg);//这里使用ToastController
    return {success: false, msg: msg};
  }


}
